<template>
  <div class="employee-list-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入员工姓名"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
      <div class="operation-area">
        <el-button type="primary" size="small" @click="handleAdd">新增员工</el-button>
      </div>
    </div>

    <!-- 员工列表表格 -->
    <el-table 
      :data="employeeList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="50px"  align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="UserId" label="用户ID" width="100px"  align="center"></el-table-column>
      <el-table-column prop="Name" label="姓名"></el-table-column>
      <el-table-column prop="Iphone" label="手机号" ></el-table-column>
      <el-table-column prop="sex" label="性别" width="100px"  align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.sex === 1 ? 'primary' : 'success'">
            {{ scope.row.sex === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 新增员工弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="姓名" prop="Name">
          <el-input v-model="form.Name" placeholder="请输入员工姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="Iphone">
          <el-input v-model="form.Iphone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, addEmployee, editEmployee, deleteEmployee } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';

export default {
  name: 'EmployeeListView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      
      // 表格数据
      employeeList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 弹窗相关
      dialogVisible: false,
      submitLoading: false,
      isEdit: false,

      // 表单数据
      form: {
        UserId: null,
        Name: '',
        Iphone: '',
        sex: 1
      },

      // 表单验证规则
      rules: {
        Name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        Iphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑员工' : '新增员工';
    }
  },
  methods: {
    // 获取员工列表
    async fetchEmployeeList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          keyword: this.searchKeyword,
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        const response = await getEmployeeList(params);
        console.log(response);
        if (response.data.code) {
          // API成功返回数据
          console.log(1)
          const rawData = response.data.data.data || [];
          // 处理数据，将Sex字段映射为sex
          this.employeeList = rawData.map(item => ({
            ...item,
            sex: item.Sex || item.sex || 1 // 兼容Sex和sex字段
          }));
          this.total = response.data.data.total || 0;
        } else {
          
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error('获取员工列表失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取员工列表失败');
        }
      } finally {
        this.loading = false;
      }
    },

    // 新增员工
    handleAdd() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.resetForm();
    },

    // 编辑员工
    handleEdit(row) {
      this.isEdit = true;
      this.form = {
        UserId: row.UserId,
        Name: row.Name,
        Iphone: row.Iphone,
        sex: row.sex
      };
      this.dialogVisible = true;
    },

    // 删除员工
    handleDelete(row) {
      this.$confirm(`确认要删除员工"${row.Name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        try {
          const response = await deleteEmployee(row.UserId);
          if (response.data && response.data.code === 1) {
            this.$message.success('删除成功');
            this.fetchEmployeeList();
          } else {
            this.$message.error('删除失败');
          }
        } catch (error) {
          console.error('删除员工失败:', error);
          if (checkTokenFromError(error)) {
            // Token无效或过期
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
          } else {
            // 其他错误
            this.$message.error('删除失败');
          }
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 检查token是否存在
          if (!checkToken()) {
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
            return;
          }

          this.submitLoading = true;
          
          try {
            let response;
            if (this.isEdit) {
              response = await editEmployee(this.form);
            } else {
              response = await addEmployee(this.form);
            }
            
            if (response.data && response.data.code === 1) {
              this.$message.success(this.isEdit ? '编辑成功' : '新增成功');
              this.dialogVisible = false;
              this.fetchEmployeeList();
            } else {
              this.$message.error(response.data.msg);
            }
          } catch (error) {
            console.error(this.isEdit ? '编辑失败:' : '新增失败:', error);
            if (checkTokenFromError(error)) {
              // Token无效或过期
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              // 其他错误
              this.$message.error(response.data.msg);
            }
          } finally {
            this.submitLoading = false;
          }
        }
      });
    },

    // 重置表单
    resetForm() {
      this.form = {
        UserId: null,
        Name: '',
        Iphone: '',
        sex: 1
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchEmployeeList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.currentPage = 1;
      this.fetchEmployeeList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchEmployeeList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchEmployeeList();
    }
  },
  
  created() {
    this.fetchEmployeeList();
  }
};
</script>

<style scoped>
.employee-list-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式 */
.el-table {
  border: 1px solid #EBEEF5;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}
</style> 